﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Linq;
using ECG.Common;
using ECG.DAL;
using ECG.Utility;
using ECG.WebUI.Infrastructure;
using ECG.WebUI.Models;
using ImageResizer;

namespace ECG.WebUI.CustomHelpers
{
    public class FunctionHelpers
    {

        public static string UploadImages(out string error, string fullFolder, HttpPostedFileBase fileUpload)
        {
            var isValid = true;
            var fileName = string.Empty;
            var filePathSaved = string.Empty;
            var e = "";
            //var url = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["CategoryImagesPath"]);
            var name = fileUpload.FileName;
            if (string.Compare(fileUpload.ContentType, "image/png", true) != 0 &&
                string.Compare(fileUpload.ContentType, "image/jpeg", true) != 0 &&
                string.Compare(fileUpload.ContentType, "image/gif", true) != 0)
            {
                e = "Bạn phải sử dụng file ảnh có định dạng jpg, png, gif.";
                isValid = false;
            }
            if (isValid)
            {
                try
                {
                    var extension = Path.GetExtension(fileUpload.FileName) ?? "";
                    fileName = Path.GetFileName(string.Format("{0}-{1}.{2}", StringUtil.RemoveSpecialCharactersVn(name.Replace(extension, "")).GetNormalizeString(), GenerateId(), "jpg"));
                    if (!Directory.Exists(fullFolder)) Directory.CreateDirectory(fullFolder);
                    fileUpload.SaveAs(Path.Combine(fullFolder, fileName ?? ""));
                    filePathSaved = fileName;
                }
                catch (Exception ex)
                {
                    e = ex.Message;
                }
            }
            error = e;
            return filePathSaved;
        }

        public static string UploadDocument(string name, string url, out string error, string oldFileName, HttpPostedFileBase fileUpload)
        {
            var isValid = false;
            var fileName = string.Empty;
            string e = "";
            string a = fileUpload.ContentType;
            if (fileUpload != null)
            {
                isValid = true;
                if (string.Compare(fileUpload.ContentType, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", true) != 0 &&
                    string.Compare(fileUpload.ContentType, "application/msword", true) != 0 &&
                    string.Compare(fileUpload.ContentType, "application/pdf", true) != 0 &&
                    string.Compare(fileUpload.ContentType, "application/x-pdf", true) != 0)
                {
                    e = "Bạn phải sử dụng file ảnh có định dạng jpg, png, gif.";
                    isValid = false;
                }
                if (isValid)
                {
                    var extension = Path.GetExtension(fileUpload.FileName);
                    fileName = Path.GetFileName(string.Format("{0}-{1}{2}", StringUtil.RemoveSpecialCharactersVn(name.GetNormalizeString()),
                                                       (new Random()).Next(9999), extension));
                    fileUpload.SaveAs(url + fileName);
                    var odlPicturePath = string.Format("{0}{1}", url, oldFileName);
                    if (System.IO.File.Exists(odlPicturePath))
                    {
                        System.IO.File.Delete(odlPicturePath);
                    }

                }
            }
            error = e;
            return fileName;
        }

        public static string EnCryptData(string strSource)
        {
            var md5Hasher = new MD5CryptoServiceProvider();
            byte[] btys = null;
            var strDes = string.Empty;
            var encoder = new UTF8Encoding();
            btys = md5Hasher.ComputeHash(encoder.GetBytes(strSource));
            for (int i = 0; i <= btys.Length - 1; i++)
            {
                strDes += btys[i];
            }
            return strDes;
        }

        public static string GenerateId()
        {
            return MD52INT(Guid.NewGuid().ToString()).ToString();
        }

        public static int MD52INT(string MDKEY)
        {
            int TOTAL = 0;
            for (int i = 0; i < MDKEY.Length - 1; i++)
            {
                TOTAL += CHAR2INT(MDKEY.Substring(i, 1));
            }
            return TOTAL;
        }

        private static int CHAR2INT(string MYCHAR)
        {
            int NUM = 100;
            switch (MYCHAR)
            {
                case "A":
                    NUM = 19902;
                    break;
                case "B":
                    NUM = 15604;
                    break;
                case "C":
                    NUM = 17505;
                    break;
                case "D":
                    NUM = 15562;
                    break;
                case "E":
                    NUM = 18752;
                    break;
                case "F":
                    NUM = 1765712;
                    break;
                case "0":
                    NUM = 155675;
                    break;
                case "1":
                    NUM = 26767;
                    break;
                case "2":
                    NUM = 2567562;
                    break;
                case "3":
                    NUM = 15675692;
                    break;
                case "4":
                    NUM = 2567532;
                    break;
                case "5":
                    NUM = 1575682;
                    break;
                case "6":
                    NUM = 535392;
                    break;
                case "7":
                    NUM = 15354346;
                    break;
                case "8":
                    NUM = 1723427;
                    break;
                case "9":
                    NUM = 1342399;
                    break;
            }
            return NUM;
        }

        public static List<string> BuildListKeyword(string keyword)
        {
            var result = new List<string>();
            var words = keyword.Split(new char[] { '%', ' ' }).ToList();

            var tempKeyword = string.Join(" and ", words.ToArray());
            var lastKeyword = string.Join(" or ", words.ToArray());
            result.Add(tempKeyword);

            while (words.Count > 1)
            {
                words.RemoveAt(words.Count - 1);
                tempKeyword = string.Join(" and ", words.ToArray());
                result.Add(tempKeyword);
            }

            result.Add(lastKeyword);

            return result;
        }

        public static string StripDiacritics(string accented, string replaceby)
        {
            if (string.IsNullOrEmpty(accented)) return string.Empty;
            string strRtn;
            var regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string strFormD = accented.Normalize(NormalizationForm.FormD);
            strRtn = regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
            strRtn = Regex.Replace(strRtn, "[^a-zA-Z0-9]", replaceby);
            string dup = replaceby + replaceby;//neu co 2 ki tu thay the trung nhau thi chi nhan mot cai
            if (string.IsNullOrEmpty(dup)) return strRtn;
            while (strRtn.Contains(dup))
            {
                strRtn = strRtn.Replace(dup, replaceby);
            }
            return strRtn.Trim();
        }

        /// <summary>
        /// Sinh ra so string la chuoi cac so
        /// </summary>
        /// <param name="Length">length</param>
        /// <returns>string</returns>
        public static string GenerateRandomDigitCode(int Length)
        {
            var random = new Random();
            string s = "";
            for (int i = 0; i < Length; i++)
                s = String.Concat(s, random.Next(10).ToString());
            return s;
        }

        /// <summary>
        /// Get Current Url
        /// </summary>
        /// <returns></returns>
        public static string GetUrlOriginal()
        {

            var url = string.Format("{0}://{1}{2}{3}",
                                    HttpContext.Current.Request.Url.Scheme,
                                    HttpContext.Current.Request.Url.Host,
                                    HttpContext.Current.Request.Url.Port == 80
                                        ? string.Empty : ":" + HttpContext.Current.Request.Url.Port,
                                    HttpContext.Current.Request.ApplicationPath);
            return url;

        }


        /// <summary>
        ///     Sinh ra mang int chua dung 5 phan tu lien tiep phuc vu cho pading kieu moi
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="totalPages"></param>
        /// <param name="itemPerPage"></param>
        /// <returns></returns>
        public static int[] GenerateArrIntForPaging(int currentPage, int totalPages, int itemPerPage)
        {
            var arr = new int[itemPerPage];
            if ((currentPage <= 5) & (totalPages <= 5))
            {
                arr = new int[totalPages];
                for (var i = 0; i < totalPages; i++)
                {
                    arr[i] = i + 1;
                }
                return arr;
            }

            if ((currentPage <= 3) & (totalPages > 5))
            {
                for (var i = 0; i < itemPerPage; i++)
                {
                    arr[i] = i + 1;
                }
                return arr;
            }

            if ((currentPage >= 4) & (totalPages > 5))
            {
                arr[0] = currentPage - 2;
                arr[1] = currentPage - 1;
                arr[2] = currentPage;
                arr[3] = currentPage + 1;
                arr[4] = currentPage + 2;
            }

            // 2 so cuoi
            if (currentPage == (totalPages - 1))
            {
                arr[0] = currentPage - 3;
                arr[1] = currentPage - 2;
                arr[2] = currentPage - 1;
                arr[3] = currentPage;
                arr[4] = currentPage + 1;
            }

            if (currentPage == totalPages)
            {
                arr[0] = currentPage - 4;
                arr[1] = currentPage - 3;
                arr[2] = currentPage - 2;
                arr[3] = currentPage - 1;
                arr[4] = currentPage;
            }

            if (currentPage > totalPages)
            {
                arr[0] = totalPages - 4;
                arr[1] = totalPages - 3;
                arr[2] = totalPages - 2;
                arr[3] = totalPages - 1;
                arr[4] = totalPages;
            }

            return arr;
        }

        /// <summary>
        /// Get menu list third level for drop down list
        /// </summary>
        /// <returns></returns>
        public static List<ProductCategoryDto> GetMenuListThreeLevel()
        {
            var result = new List<ProductCategoryDto>();
            var menuList = ProductCategoryDb.GetAll() ?? new List<ProductCategoryDto>();
            var topMenuList = (from m in menuList where m.ParentId == "0" select m);
            foreach (var item in topMenuList)
            {
                result.Add(item);
                var subMenuList = (menuList.Where(m => m.ParentId == item.Id));
                foreach (var subItem in subMenuList)
                {
                    subItem.Name = "----" + subItem.Name;
                    result.Add(subItem);
                    var childMenuList = (from m in menuList where m.ParentId == subItem.Id select m);
                    foreach (var childItem in childMenuList)
                    {
                        childItem.Name = "----------" + childItem.Name;
                        result.Add(childItem);
                    }
                }
            }
            result.Insert(0, new ProductCategoryDto { Id = "0", Name = "-- Danh mục sản phẩm --" });
            return result;
        }

        /// <summary>
        /// Create product image thumbnail from xml template
        /// </summary>
        /// <param name="fullFolder"></param>
        /// <param name="fileName"></param>
        /// <param name="tempPathProductThumb"></param>
        /// <param name="imageFile"></param>
        public static void CreateProductThumbnail(string fullFolder, string fileName, string tempPathProductThumb, HttpPostedFileWrapper imageFile)
        {
            var sForThumbnail = from c in XElement.Load(HttpContext.Current.Server.MapPath(tempPathProductThumb)).Elements("size") select c;
            var sForThumbnailList = sForThumbnail.Select(xElement => xElement.FirstAttribute.Value).ToList();
            foreach (var item in sForThumbnailList)
            {
                var fullFolderThumb = Path.Combine(fullFolder, item);
                var width = int.Parse(item.Split('x')[0]);
                var height = int.Parse(item.Split('x')[1]);
                if (!Directory.Exists(fullFolderThumb))
                    Directory.CreateDirectory(fullFolderThumb);
                var imageThumbPath = Path.Combine(fullFolderThumb, fileName);
                var i = new ImageJob(imageFile, imageThumbPath, new ResizeSettings(width, height, FitMode.Pad, "jpg"));
                i.Build();
            }
        }


        /// <summary>
        /// Create product thumbnail from file
        /// </summary>
        /// <param name="fullFolderThumbnail"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="fileName"></param>
        /// <param name="tempPathProductThumb"></param>
        /// <param name="relativePathFile"></param>
        public static void CreateProductThumbnailFromFile(string fullFolderThumbnail, int width, int height, string fileName, string tempPathProductThumb, string relativePathFile)
        {
            var imageFile = new FileStream(relativePathFile, FileMode.Open, FileAccess.ReadWrite);
            var imageThumbPath = Path.Combine(fullFolderThumbnail, fileName);
            var extension = Path.GetExtension(imageThumbPath);
            if (extension != null && !extension.Equals(".db"))
            {
                var i = new ImageJob(imageFile, imageThumbPath, new ResizeSettings(width, height, FitMode.Pad, "jpg"));
                i.Build();
            }
            imageFile.Close();
        }

        /// <summary>
        /// Delete product images
        /// </summary>
        /// <param name="imagePath"></param>
        /// <param name="imageName"></param>
        public static bool DeleteProductImages(string imagePath, string imageName)
        {
            // Delete root image
            var result = false;
            try
            {
                var rootFile = HttpContext.Current.Server.MapPath(imagePath + "/" + imageName);
                var pathFileThumb = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ProductTemplateForThumbnail"]);
                if (File.Exists(rootFile))
                {
                    File.Delete(rootFile);
                }
                var sProductThumbXML = (from c in XElement.Load(pathFileThumb).Elements("size") select c).Select(xElement => xElement.FirstAttribute.Value).ToList();
                foreach (var xElement in sProductThumbXML)
                {
                    var fileThumb = HttpContext.Current.Server.MapPath(imagePath + "/" + xElement + "/" + imageName);
                    if (File.Exists(fileThumb))
                        File.Delete(fileThumb);
                }
                result = true;
            }
            catch { }
            return result;
        }


      
        /// <summary>
        /// Get host name
        /// </summary>
        /// <returns></returns>
        public static string GetHostName()
        {
            var uri = HttpContext.Current.Request.Url;
            var url = uri.Scheme + Uri.SchemeDelimiter + uri.Host + (uri.Port.ToString().Equals("80") ? "" : ":" + uri.Port.ToString());
            return url;
        }

        /// <summary>
        /// Get full url
        /// </summary>
        /// <returns></returns>
        public static string GetFullUrl()
        {
            var uri = HttpContext.Current.Request.Url.AbsoluteUri;
            return uri;
        }

        /// <summary>
        /// Remove special characters
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RemoveSpecialCharsV2(string str)
        {
            //check
            str = Regex.Replace(str, @"[^\w\.@-]", " ");
            str = Regex.Replace(str, "[.()]", " ", RegexOptions.Compiled);
            var r = new Regex(@"\s+");
            str = r.Replace(str, @" ").Trim();
            return str;
        }

        /// <summary>
        /// Lay danh sach tinh thanh quan huyen tu file Country.xml
        /// </summary>
        /// <returns></returns>
        public static List<ProvinceModel> GetProvinceList()
        {
            XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/Templates/Country.xml"));

            var regions = from region in xmlDoc.Descendants("Rows")
                          where int.Parse(region.Element("ParentID").Value) == 0
                          select new
                          {
                              TinhThanhID = region.Element("TinhThanhID").Value,
                              Name = region.Element("Name").Value,
                              ParentID = region.Element("ParentID").Value,
                          };

            var tinhThanhList = new List<ProvinceModel>();

            foreach (var region in regions)
            {
                tinhThanhList.Add(new ProvinceModel()
                {
                    ProvinceId = region.TinhThanhID,
                    ProvinceName = region.Name
                });
            }
            return tinhThanhList;
        }

        /// <summary>
        /// Lay danh sach quan huyen tu file Country.xml
        /// </summary>
        /// <returns></returns>
        public static List<DistrictModel> GetDistrictList(int tinhThanhId)
        {
            XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/Templates/Country.xml"));

            var regions = from region in xmlDoc.Descendants("Rows")
                          where int.Parse(region.Element("ParentID").Value) == tinhThanhId
                          select new
                          {
                              TinhThanhID = region.Element("TinhThanhID").Value,
                              Name = region.Element("Name").Value,
                              ParentID = region.Element("ParentID").Value,
                          };

            var quanHuyenList = new List<DistrictModel>();

            foreach (var region in regions)
            {
                quanHuyenList.Add(new DistrictModel()
                {
                    DistrictId = region.TinhThanhID,
                    DistrictName = region.Name
                });
            }
            return quanHuyenList;
        }

        public static string returnConfig(string nodeName)
        {
            var elementValue = "";
            try { 
            var pathfile = ConfigurationManager.AppSettings["HostContainImages"] + "/ECGsystem.xml";
            var xmldoc = XDocument.Load(pathfile);
            
            if (xmldoc.Root != null)
            {
                elementValue = (from item in xmldoc.Descendants("ECGsystem")
                                    select (string)item.Element(nodeName)).SingleOrDefault();
            }
            }
            catch { }
            return elementValue;
        }
        public static bool SendMailRegisterSucccess(string cusName, string cusMail)
        {
            try
            {
                var mailFrom = "";
                var mailTo = cusMail;
                var mailCC = returnConfig("EmailCc"); //System.Configuration.ConfigurationManager.AppSettings["CCOrderMail"] + ";" + System.Configuration.ConfigurationManager.AppSettings["ReceiveOrderMail"];
                string subject = "Kích hoạt tài khoản mới đăng ký " + HttpContext.Current.Request.Url.Host;
                var emailContent = string.Empty;

                //reading email template
                var content = ReadMailTemplate("~/Templates/Email/RegisterMailTemplate.xml");
                emailContent = string.Format(content, cusName);
                return SmtpEmailSender.Send(mailFrom, mailTo, mailCC, subject, emailContent);
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Read XML Template
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ReadMailTemplate(string path)
        {
            // reading email template
            var doc = XDocument.Load(HttpContext.Current.Server.MapPath(path));
            if (doc.Root != null)
            {
                var content = doc.Root.Element("content");
                if (content == null) throw new ArgumentNullException("content");
                return content.Value;
            }
            return "";
        }

        /// <summary>
        /// Caculate total money in order
        /// </summary>
        /// <param name="orderInfo"></param>
        /// <param name="pInfo"></param>
        /// <returns></returns>
        public static OrderInfo CalTotalOrder(OrderInfo orderInfo, ProductOrderInfo pInfo)
        {
            decimal totalMoney = 0;
            if (pInfo != null)
            {
                var checkContain = false;
                if (orderInfo.ProductOrderList.Any(item => item.ProductId.Equals(pInfo.ProductId)))
                {
                    orderInfo.ProductOrderList.Single(x => x.ProductId == pInfo.ProductId).ProductQuantity += pInfo.ProductQuantity;
                    checkContain = true;
                }

                if (!checkContain) orderInfo.ProductOrderList.Add(pInfo);
            }

            foreach (var pItem in orderInfo.ProductOrderList)
            {
                if (pItem.PromotionPrice > 0)
                {
                    totalMoney += pItem.PromotionPrice * pItem.ProductQuantity;
                }
                else
                {
                    totalMoney += pItem.RootPriceProduct * pItem.ProductQuantity;
                }
            }
            orderInfo.TotalMoney = totalMoney;

            // customer information
            if (HttpContext.Current.Session[SessionConfig.SessionCustomerLogin] != null)
            {
                var customerInfo = (CustomerInfo)HttpContext.Current.Session[SessionConfig.SessionCustomerLogin];
                orderInfo.CustomerId = customerInfo.CustomerId;
                orderInfo.FullName = customerInfo.FullName;
                orderInfo.Email = customerInfo.Email;
                orderInfo.Telephone = customerInfo.Telephone;
                orderInfo.MobilePhone = customerInfo.MobilePhone;
                orderInfo.Address = customerInfo.Address;
                orderInfo.DistrictId = customerInfo.DistrictId;
                orderInfo.DistrictName = customerInfo.DistrictName;
                orderInfo.ProvinceId = customerInfo.ProvinceId;
                orderInfo.ProvinceName = customerInfo.ProvinceName;
                orderInfo.Gender = customerInfo.Gender;
            }
            return orderInfo;
        }

        /// <summary>
        /// Send a email that has order information
        /// </summary>
        /// <param name="bo"></param>
        /// <returns></returns>
        public static bool SendOrderMail(OrderInfo bo)
        {
            try
            {
                if (bo != null)
                {
                    var subject = new StringBuilder();
                    var mailTo = bo.Email;
                    #region info setting
                    var mailCC = ECG.Utility.Common.returnConfig("EmailCc");
                    var ecgDomain = ECG.Utility.Common.returnConfig("Domainname");
                    #endregion
                    var mailFrom = "";
                    if (!string.IsNullOrEmpty(mailTo))
                    {
                        subject.AppendFormat("Đơn đặt hàng - {0} - {1} - {2}", bo.FullName, bo.MobilePhone, DateTime.Now.ToString("dd/MM/yyyy"));

                        var templMailOrder = "";
                        var headerMail = string.Format(ReadMailTemplate("~/Templates/Email/OrderEmailTemplates/HeaderTemplate.xml"), bo.FullName, bo.OrderId, DateTime.Now, bo.FullName, bo.MobilePhone, bo.OrderId, bo.Email, "", bo.Payment, bo.ProvinceName, bo.DistrictName, bo.Address);

                        var productList = bo.ProductOrderList;
                        if (productList != null && productList.Count > 0)
                        {
                            var count = 0;
                            foreach (var item in productList)
                            {
                                if (item.ProductId.Contains("_")) item.ProductId = item.ProductId.Split('_')[0];
                                count += 1;
                                templMailOrder += " <tr>";
                                templMailOrder += " <td align='center' style='border-bottom: 1px solid #DDD;border-right: 1px solid #DDD;padding: 15px 10px;'>" + count + "</td>";
                                templMailOrder += " <td align='left' style='border-bottom: 1px solid #DDD;border-right: 1px solid #DDD;padding: 15px 10px;'>";
                                templMailOrder += " <span style='padding-top: 10px;display:block;'>";
                                templMailOrder += " <a style='color: #004C94;text-decoration:none;' href='" + @ecgDomain + "/" + string.Format("{0}-{1}.html", StringUtil.RemoveSpecialCharactersVn(item.ProductName), item.ProductId) + "'>" + item.ProductName + "</a>";
                                templMailOrder += " </span>";
                                templMailOrder += " <br/><span>";
                                if (!string.IsNullOrEmpty(item.ProductSizeId))
                                {
                                    templMailOrder += string.Format("<font color='#999'>Bạn chọn</font> {0} ", item.ProductSizeName);
                                }
                                if (!string.IsNullOrEmpty(item.ProductColor))
                                {
                                    if (string.IsNullOrEmpty(item.ProductSizeId)) templMailOrder += "- ";
                                    templMailOrder += string.Format("{0}", item.ProductColor);
                                }
                                templMailOrder += " </span>";
                                templMailOrder += " </td>";
                                templMailOrder += " <td align='center' style='border-bottom: 1px solid #DDD;border-right: 1px solid #DDD;padding: 15px 10px;'>";
                                templMailOrder += " <span>" + item.ProductQuantity + "</span>";
                                templMailOrder += " </td>";
                                templMailOrder += " <td align='center' style='border-bottom: 1px solid #DDD;border-right: 1px solid #DDD;padding: 15px 10px;'>";
                                templMailOrder += " <span class='ColorOrange'><span>" + string.Format("{0}", item.PromotionPrice > 0 ? (item.PromotionPrice * item.ProductQuantity).ToString("#,###") : (item.RootPriceProduct * item.ProductQuantity).ToString("#,###")) + "</span> đ</span>";
                                templMailOrder += " </td>";
                                templMailOrder += " </tr>";
                            }

                        }
                        var footerMail = string.Format(ReadMailTemplate("~/Templates/Email/OrderEmailTemplates/FooterTemplate.xml"), bo.TotalMoney.ToString("#,###"), bo.TotalMoney.ToString("#,###"), bo.Comment);
                        var contentEmail = headerMail + templMailOrder + footerMail;
                        return SmtpEmailSender.Send(mailFrom, mailTo, mailCC, subject.ToString(), contentEmail);
                    }
                }
            }
            catch
            {
                return false;
            }
            return false;
        }

        /// <summary>
        /// Insert customer register into customer table
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool InsertCustomerRegister(RegisterInOrderModel model)
        {
            var passwordSalt = Guid.NewGuid().ToString();
            var password = model.Password.CreatePasswordHash(passwordSalt);
            var customerInfo = new CustomerDto
                                   {
                                       Id = GenerateId(),
                                       FullName = model.FullName,
                                       Password = password,
                                       PasswordSalt = passwordSalt,
                                       Email = model.Email,
                                       Birthday = DateTime.Parse(model.Day + "/" + model.Month + "/" + model.Year),
                                       Gender = model.Gender,
                                       Address = model.Address,
                                       Telephone = model.Telephone,
                                       Mobilephone = model.MobilePhone,
                                       ProvinceId = int.Parse(model.ProvinceId),
                                       ProvinceName = model.ProvinceName,
                                       DistrictId = int.Parse(model.DistrictId),
                                       DistrictName = model.DistrictName
                                   };
            if (CustomerDb.Add(customerInfo) > 0)
            {
                customerInfo.EmailStatus = SendMailRegisterSucccess(customerInfo.FullName, customerInfo.Email);
                CustomerDb.Update(customerInfo);

                var customerInfoLogin = new CustomerInfo
                {
                    Address = customerInfo.Address,
                    BirthDay = customerInfo.Birthday,
                    CustomerId = customerInfo.Id,
                    DistrictId = customerInfo.DistrictId.ToString(),
                    DistrictName = customerInfo.DistrictName,
                    Email = customerInfo.Email,
                    FullName = customerInfo.FullName,
                    Gender = customerInfo.Gender,
                    MobilePhone = customerInfo.Mobilephone,
                    ProvinceId = customerInfo.ProvinceId.ToString(),
                    ProvinceName = customerInfo.ProvinceName,
                    Telephone = customerInfo.Telephone
                };
                HttpContext.Current.Session[SessionConfig.SessionCustomerLogin] = customerInfoLogin;
                return true;
            }
            return false;
        }

        /// <summary>
        /// Insert information into order and orderdetail table
        /// </summary>
        /// <returns></returns>
        public static bool InsertOrder(OrderInfo model, RegisterInOrderModel customer, string payment, string comment)
        {
            // Luu ORDER
            // Check Info Login
            model.OrderId = GenerateId();
            if (!customer.IsAddressDiff)
            {
                model.Email = customer.Email;
                model.FullName = customer.FullNameAddition;
                model.MobilePhone = customer.PhoneAddition;
                model.Telephone = customer.Telephone;
                model.Address = customer.AddressAddition;
                model.ProvinceId = customer.ProvinceIdAdd;
                model.ProvinceName = customer.ProvinceNameAdd;
                model.DistrictId = customer.DistrictIdAdd;
                model.DistrictName = customer.DistrictNameAdd;
                model.Gender = customer.Gender;
                model.Payment = payment;
                model.Comment = comment;
            }
            else
            {
                model.Email = customer.Email;
                model.FullName = customer.FullName;
                model.MobilePhone = customer.MobilePhone;
                model.Telephone = customer.Telephone;
                model.Address = customer.Address;
                model.ProvinceId = customer.ProvinceId;
                model.ProvinceName = customer.ProvinceName;
                model.DistrictId = customer.DistrictId;
                model.DistrictName = customer.DistrictName;
                model.Gender = customer.Gender;
                model.Payment = payment;
                model.Comment = comment;
            }
            var order = new OrderDto
                            {
                                OrderId = model.OrderId,
                                CustomerId = model.CustomerId,
                                ReceiveDate = DateTime.Now,
                                Email = model.Email,
                                FullName = model.FullName,
                                MobilePhone = model.MobilePhone,
                                Telephone = model.Telephone,
                                Address = model.Address,
                                ProvinceId = model.ProvinceId,
                                ProvinceName = model.ProvinceName ?? "",
                                DistrictId = model.DistrictId ?? "",
                                DistrictName = model.DistrictName,
                                Payment = model.Payment,
                                TotalMoney = model.TotalMoney,
                                ShippingCost = 0,
                                Discount = 0,
                                Comment = model.Comment,

                            };
            OrderDb.Add(order);

            // Luu ORDER DETAIL
            foreach (var item in model.ProductOrderList)
            {
                var orderDetail = new OrderDetailDto();
                orderDetail.OrderId = model.OrderId;
                if (item.PromotionPrice > 0)
                {
                    orderDetail.Price = item.PromotionPrice;
                }
                else
                {
                    orderDetail.Price = item.RootPriceProduct;
                }
                orderDetail.ProductId = item.ProductId;
                orderDetail.Quantity = item.ProductQuantity;
                OrderDetailDb.Add(orderDetail);
            }

            // Create session order
            HttpContext.Current.Session[SessionConfig.SessionCartInfor] = model;
            return SendOrderMail(model);
        }

        /// <summary>
        /// Gửi mail thông báo đến khách hàng đăng ký nhận mã số xổ số
        /// </summary>
        /// <param name="cusName"></param>
        /// <param name="cusMail"></param>
        /// <returns></returns>
        public static bool SendMailDangKyQuayXoSo(string cusName, string cusMail, string maSoXo)
        {
            try
            {
                var mailFrom = "";
                var mailTo = cusMail;
                var mailCC = ConfigurationManager.AppSettings["ccOrder"];
              
                const string subject = "Thông báo mã số quay số trúng thưởng tại babo.vn nhân dịp 20-11";
                var emailContent = string.Empty;

                //reading email template
                var content = ReadMailTemplate("~/Templates/Email/Campaign/20-11/RegisterQuaySoXoTemplate.xml");
                emailContent = string.Format(content, cusName, maSoXo);
                return SmtpEmailSender.Send(mailFrom, mailTo, mailCC, subject, emailContent);
            }
            catch (Exception)
            {
                return false;
            }
        }

        //Get WebInfo
        public static WebInfoDto GetWebInfo()
        {
            var modelInfo = new WebInfoDto();
            try
            {
                modelInfo = HttpContext.Current.Session[SessionConfig.SessionWebInfo] as WebInfoDto;
            }catch
            {
            }
            if (modelInfo == null)
            {
                var modelWeb = new List<WebInfoDto>();
                try
                {
                    modelWeb = WebInfoDb.GetAll();
                }
                catch { }

                if (modelWeb.Any())
                {
                    HttpContext.Current.Session[SessionConfig.SessionWebInfo] = modelWeb[0];
                }
                else
                {
                    HttpContext.Current.Session[SessionConfig.SessionWebInfo] = new WebInfoDto();
                }
                modelInfo = HttpContext.Current.Session[SessionConfig.SessionWebInfo] as WebInfoDto;
            }
            return modelInfo;
        }
    }
}